<script lang="ts" setup>
import type{ MessageProps } from './types';
import {ref , onMounted,watch, computed,nextTick, type Ref} from 'vue'
import RenderVnode from '../Common/RenderVnode';
import Icon from '../Icon/Icon.vue';
import { getLastBottomOffset } from './method';
import { useAddThing } from '@/hooks/useAddThing';

function handleFn (e:Event){
  const ee = e as KeyboardEvent
  if(ee.code === 'Escape'){
    visible.value = false
  }
}
useAddThing(document,'keydown',handleFn)
const props = withDefaults(defineProps<MessageProps>(),{
  type:'info',
  duration:3000,
  gapOffset:20
})

// 需要拿到 该 message 的ref,方便根据dom 节点的属相仅限跟高度计算
const messageRef = ref<HTMLDivElement | null>(null);
// 这个 div 组件 的高度
const height = ref(0)
// 上一个组件的底部位置
const lastOffset = computed(()=>getLastBottomOffset(props.id-1))
//  相对于视口的高度
const topOffset = computed(()=>{
  return props.gapOffset + lastOffset.value!
})
// 为下一个元素 预留 offset (下一个通过 函数获取)
const bottomOffset = computed(()=>topOffset.value + height.value)


const positionStyle = computed(()=>{
  return {
    top:`${topOffset.value}px`,
    zIndex:props.zIndex,
  }
})

const visible = ref(false)
let timer:any = null
function clearTimer (){
  if(props.duration === 0)return
  
  clearTimeout(timer)
  console.log("鼠标进来了，停止倒计时")
}
function startTimer (){
  if(props.duration === 0)return
  // 定时器
  console.log("开始倒计时")
  timer = setTimeout(()=>{
    visible.value = false
  },props.duration)
}
onMounted( async ()=>{
  visible.value = true
  useAddThing(messageRef ,'mouseenter',clearTimer)
  useAddThing(messageRef ,'mouseleave',startTimer)
  startTimer()
  // 等到 Dom 更新以后
  await nextTick()
  height.value = messageRef.value!.getBoundingClientRect().height
  console.log(`上一个bottomoffset:${lastOffset.value},本组件的top：${topOffset.value},本组件的高度:${height.value},本组件的bottomoffset:${bottomOffset.value}`)
})

watch(visible,(newValue)=>{
  if(!newValue){
    props.onDestroy()// 销毁message 组件
  }
})

defineExpose({
  bottomOffset,
  visible,
})
</script>
<template>
<div
ref="messageRef"
v-show="visible"
class="wk-message"
:class="{
  [`wk-message--${type}`]:type,
  'is-close':showClose
  }"
role="alert"
:style="positionStyle"
>
  <!-- 内容容器 -->
  <div class="wk-message__content" >
    <slot>
      <RenderVnode :v-node="message"></RenderVnode>
    </slot>
  </div>
  <!-- 控制关闭的容器 -->
  <div class="wk-message__close" v-if="showClose">
    <div @click.stop="$event=>visible = false"><Icon  icon="xmark"></Icon></div>
    
  </div>
</div>
</template>
<style>
.wk-message{
  width: max-content;
  /* 绝对定位，浏览器视口为参照点 */
  position: fixed;
  left: 50%;
  /* top:20px; */
  transform:translateX(-50%);
  border:2px solid pink;
}
</style>